﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace iLangl.Customer.DAL.XMLStorage
{
	public class SecurityDAL : BaseStorageDAL, ISecurityDAL
	{
		#region ISecurityDAL Members

		public string AuthenticateUser(string userName, string password)
		{
			foreach (dtoXmlStorage.UserAccountsRow cr in Storage.UserAccounts)
			{
				if (cr.IsPasswordNull())
					continue;

				if(
					(string.Compare(cr.UserName.Trim(),userName.Trim(), true) == 0)
					&&(string.Compare(cr.Password.Trim(),password.Trim(), true) == 0))
				{
					return cr.Id;
				}
			}

			return string.Empty;
		}


		public void RegisterUser(string userName, string password, IDbTransaction trans)
		{

			dtoXmlStorage.UserAccountsRow userRow = null;


			foreach (dtoXmlStorage.UserAccountsRow uar in Storage.UserAccounts)
			{
				if (String.Compare(userName.Trim(), uar.UserName) == 0)
				{
					userRow = uar;
					break;
				}
			}

			bool isnew = (userRow == null);

			if (isnew)
			{
				userRow = Storage.UserAccounts.NewUserAccountsRow();
				userRow.Id = Guid.NewGuid().ToString();
			}

			
			userRow.UserName = userName;
			userRow.Password = password;

			if (isnew)
			{
				Storage.UserAccounts.AddUserAccountsRow(userRow);
			}

			if (trans == null)
			{
				AcceptChanges();
			}
				
		}

		#endregion
	}
}
